﻿using System;
using Books.Model;
using RefLib.Data;

namespace Books.DAL.ModelProxies
{
    internal class BookProxy : BookModel
    {
        public BookProxy()
        {
            _authors = new Lazy<AuthorModel[]>(() =>
            {
                using (var db = ContextBuilder.Build<BooksContext>(BooksContext.ConnectionName))
                {
                    return db.GetAuthorsForBook(BookId);
                }
            });

            _publisher = new Lazy<PublisherModel>(() =>
            {
                using (var db = ContextBuilder.Build<BooksContext>(BooksContext.ConnectionName))
                {
                    return db.GetPublisherById(PublisherId);
                }
            });
            Publisher = _publisher.Value;   // Eager load the publisher.
        }

        public override AuthorModel[] Authors
        {
            get { return _authors.Value; }
        }

        public override PublisherModel Publisher
        {
            get { return _publisher.Value; }
        }

        private Lazy<AuthorModel[]> _authors;
        private Lazy<PublisherModel> _publisher;
    }
}
